package org.chunchu.todo.mvp.impl;

import javax.inject.Inject;
import javax.inject.Singleton;

import org.chunchu.todo.AddCategoryActivity;
import org.chunchu.todo.Main;
import org.chunchu.todo.dao.CategoryDao;
import org.chunchu.todo.dao.TaskDao;
import org.chunchu.todo.model.Category;
import org.mvp.AbstractPresenter;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;

@Singleton
public class CategoryListPresenter extends AbstractPresenter<CategoryList> {

	private int lastPositionSelected = 0;
	@Inject
	private CategoryDao categoryDao;
	@Inject
	private TaskDao taskDao;
	@Inject
	private Activity main;
	@Inject
	private TaskListPresenter taskListPresenter;

	@Override
	public void initializeWith(CategoryList activity) {
		super.initializeWith(activity);
		activity.setCategories(categoryDao.findAll());
	}

	public void changePosition(int position) {
		Category category = getActivity().getCategoryAt(position);
		lastPositionSelected = position;
		taskListPresenter.setCurrentCategory(category);
	}

	public void removeItem(int position) {
		Category category = getActivity().getCategoryAt(position);
		if (category.getId() == 1)
			return;
		categoryDao.remove(category.getId());
		taskDao.removeByCategoryId(category.getId());
		getActivity().getCategories().remove(position);
		getActivity().updateUi();
		changePosition(0);
	}

	public void editItem(int position) {
		Bundle bundle = new Bundle();
		Category category = getActivity().getCategoryAt(position);
		bundle.putSerializable(AddCategory.EXTRA_CATEGORY, category);
		Intent intent = new Intent(main, AddCategoryActivity.class);
		intent.putExtras(bundle);
		intent.setAction(Main.ACTION_EDIT);
		main.startActivity(intent);
	}

	public long getCurrentPositionId() {
		return getActivity().getCategoryAt(lastPositionSelected).getId();
	}

	public void addItem() {
		Bundle bundle = new Bundle();
		Category cate = new Category("");
		bundle.putSerializable(AddCategory.EXTRA_CATEGORY, cate);
		Intent intent = new Intent(main, AddCategoryActivity.class);
		intent.putExtras(bundle);
		intent.setAction(Main.ACTION_ADD);
		main.startActivity(intent);
	}

}
